package com.jianyun.jyzs.model;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.jianyun.jyzs.bean.TopBrodCastBean;
import com.jianyun.jyzs.http.Api;
import com.jianyun.jyzs.http.CustomCallback;
import com.jianyun.jyzs.http.RetrofitHelper;
import com.jianyun.jyzs.model.imdoel.ISplashModel;
import com.jianyun.jyzs.utils.SPUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.ResponseBody;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by yangshijun on 2018/9/20.
 */

public class SplashModel implements ISplashModel {
    private static SplashModel model;
    private static Context mContext;

    private SplashModel() {
    }

    public static SplashModel getInstance() {

        if (model == null)
            model = new SplashModel();
        return model;
    }

    @Override
    public void getSplshPicture(Context context, String Url, final String fileName, final String fileUrl, final OngetSplashListener ongetSplashListener) {
        this.mContext = context;
        Api api = RetrofitHelper.builderTopImghttp().create(Api.class);
        api.downloadPicFromNet(Url)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .map(new Func1<ResponseBody, Bitmap>() {
                    @Override
                    public Bitmap call(ResponseBody responseBody) {
                        if (responseBody != null) {
                            Log.d("test", "收到的responseBody不为空！");
                        }
                        if (writeResponseBodyToDisk(responseBody, fileName, fileUrl)) {
                            Bitmap bitmap = BitmapFactory.decodeFile((mContext.getExternalFilesDir(null) + File.separator + fileName));
                            return bitmap;
                        }
                        return null;
                    }
                })
                .subscribe(new Subscriber<Bitmap>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(Bitmap bitmap) {
                        ongetSplashListener.setBitmap(bitmap);
                    }
                });
    }

    private boolean writeResponseBodyToDisk(ResponseBody body, String fileName, String fileUrl) {//保存图片到本地
        try {
            // todo change the file location/name according to your needs

            File futureStudioIconFile = new File((mContext.getExternalFilesDir(null) + File.separator + fileName));
            Log.d("test", "文件的保存地址为：" + mContext.getExternalFilesDir(null) + File.separator + fileName);
            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                byte[] fileReader = new byte[4096];
                long fileSize = body.contentLength();
                long fileSizeDownloaded = 0;
                inputStream = body.byteStream();
                outputStream = new FileOutputStream(futureStudioIconFile);
                while (true) {
                    int read = inputStream.read(fileReader);
                    if (read == -1) {
                        break;
                    }
                    outputStream.write(fileReader, 0, read);
                    fileSizeDownloaded += read;

                    Log.d("test", "file download: " + fileSizeDownloaded / fileSize * 100);
                    Log.d("test", "file download: " + fileSizeDownloaded + " of " + fileSize);
                }
                outputStream.flush();

                SPUtils.put(mContext, "adPictureAddress", mContext.getExternalFilesDir(null) + File.separator + fileName);//下载好广告图片后，保存好当前广告图片的地址，为判断是否已经下载好图片做准备
                SPUtils.put(mContext, "adPictureUrl", fileUrl);
                return true;
            } catch (IOException e) {
                return false;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            }
        } catch (IOException e) {
            return false;
        }
    }

}
